package com.zsw.qr;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GetImg {
	
//	private static Random ran = new Random();
	private static String[] text = new String[]{"多么痛的领悟", "初时快乐终时伤悲", "太惨了真的太惨了", "年年有今日岁岁有今朝", "这么幸运必是祖上积了不少阴德", "对自己的才华和帅气只字不提", "我凭本事单的身为什么天天要被别人塞狗粮", "每天被自己帅醒的感觉你们是无法体会的", "一把年纪还可爱的很我真是个罪人", "闹钟叫起的只是我的躯壳叫不起我沉睡的心", "僵尸兴奋地打开我的脑壳然后失望地走了", "智商该充费了", "上帝的宠儿呀", "狗都不爱理你", "这辈子找个有钱的另一半", "六六六六六六"};
	private static String[] center = new String[]{"智慧", "坑骗", "能力", "乞讨", "运气", "高冷", "单身", "帅气", "可爱", "睡觉", "脑子", "脸蛋", "老天", "基友", "对象", "手艺"};

	private static Logger logger = LoggerFactory.getLogger(GetImg.class);
	@SuppressWarnings({"restriction" })
	public static BufferedImage getImg(String name, String qrContent){
		logger.info(name);
		try {
			String str = name;
			BufferedImage image = ImageIO.read(GetImg.class.getClassLoader().getResourceAsStream("template.jpg"));
			int width = image.getWidth();
			Font font = new Font("宋体", Font.BOLD, 40);
			FontMetrics metrics = sun.font.FontDesignMetrics.getMetrics(font);
//			Rectangle2D bound = metrics.getStringBounds(str, g);
			int strWidth = metrics.stringWidth(str);
			Graphics2D g = image.createGraphics();
			g.setColor(new Color(65, 105, 72));
			g.setFont(font);
			g.drawString(str, (width - strWidth)/2, 200);
			g.setFont(new Font("华文彩云", Font.BOLD, 90));
//			int index = ran.nextInt(text.length);
			int index = hash(name);
			g.drawString(center[index], (width - metrics.stringWidth(center[index]))/2 - 50, 370);
			g.setFont(font);
			float lineWidth = 300.0f;
			StringBuilder sb = new StringBuilder();
			int i = 0;
			for(char c: text[index].toCharArray()){
				sb.append(c);
				if(metrics.stringWidth(sb.toString()) > lineWidth){
					String tem = sb.toString();
					g.drawString(tem, (width - metrics.stringWidth(tem))/2, 500 + (i * 40));
					sb.delete(0, sb.length());
					i++;
				}
			}
			g.drawString(sb.toString(), (width - metrics.stringWidth(sb.toString()))/2, 500 + (i * 40));
//			g.drawImage(QRCodeUtil.createImage(qrContent, null, false), 460, 685, null);
			image.flush();
			g.dispose();
			return image;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	final static int hash(String k) {

        int h = k.hashCode();
        
        h ^= (h >>> 20) ^ (h >>> 12);
        h = h ^ (h >>> 7) ^ (h >>> 4);
        return h & (text.length - 1);
    }
	
}
